//
//  XS_SearchVC.swift
//  XueDao
//
//  Created by 韩云智 on 2020/12/9.
//

import UIKit
import RxSwift
import RxCocoa
import RxDataSources

class XS_ListM<T>: XS_BaseModel {
    var records: [T] = []
    var total = 0
    var size = 0
    var current = 0
    var searchCount = false
    var pages = 0
}

class XS_searchQueryNewsM: XS_BaseModel { // 资讯
    var shareUrl = ""
    var newsImgUrl = "" // 资讯封面图地址
    var count = 0 // 资讯浏览次数
    var label = "" // 资讯标签（可能有多个，按“，”拆分）
    var title = "" // 资讯标题
    var id = 0 // 资讯id
}
class XS_searchQueryRecruitmentM: XS_BaseModel { // 招聘
    var companyLogoUrl = "" // 招聘公司logo
    var companyName = "" // 招聘公司名称
    var detailAddress = "" // 招聘详细地址
    var workPlace = "" // 招聘工作地点
    var salaryRange = "" // 招聘薪资范围
    var minDegree = "" // 招聘最低学历
    var experienceRequirement = "" // 招聘经验要求
    var industryName = "" // 招聘行业名称
    var positionName = "" // 招聘职位名称
    var id = 0 // 招聘id
    var positionDescription = "" // 岗位描述
}
class XS_searchQueryCurriculumM: XS_BaseModel { // 课程
    var curriculumNum = 0 // 课程数
    var curriculumImgUrl = "" // 课程封面图地址
    var purchaseNum = 0 // 课程购买人数
    var vipIsFree = "" // 课程会员是否免费
    var isFree = "" // 课程是否免费
    var discountPrice = "" // 课程优惠价格
    var vipPrice = "" // 课程会员价格
    var price = "" // 课程价格
    var curriculumName = "" // 课程名称
    var id = 0 // 课程id
    var curriculumForm = "online"
    var label = "" // 标签
}

class XS_searchQueryM: XS_BaseModel {
    var curriculum = XS_ListM<XS_searchQueryCurriculumM>()
    var recruitment = XS_ListM<XS_searchQueryRecruitmentM>()
    var news = XS_ListM<XS_searchQueryNewsM>()
}


class XS_SearchVC: XS_BaseVC {
    enum SearchType {
        case curriculum(XS_searchQueryCurriculumM) // 课程
        case recruitment(XS_searchQueryRecruitmentM) // 招聘
        case news(XS_searchQueryNewsM) // 资讯
    }
    
    lazy var searchView = UIView()
    lazy var search = QMUITextField(frame: CGRect(x: 0, y: 0, width: .scale*303, height: .scale*32))
    
    private lazy var dataPS = PublishSubject<XS_searchQueryM>()
    lazy var table = UITableView(frame: .zero, style: .grouped)
    lazy var dataSource = RxTableViewSectionedReloadDataSource<SectionModel<(String, Int), SearchType>>(configureCell: { ds, tv, ip, it in
        let (text, _) = ds.sectionModels[ip.section].model
        switch text {
        case "课程":
            let cell = tv.dequeueReusableCell(withIdentifier: text, for: ip) as! XS_SearchCurriculum
            cell.modelPS.onNext(it)
            return cell
        case "就业":
            let cell = tv.dequeueReusableCell(withIdentifier: text, for: ip) as! XS_SearchRecruitment
            cell.modelPS.onNext(it)
            return cell
//        case "资讯":
//            let cell = tv.dequeueReusableCell(withIdentifier: text, for: ip) as! XS_SearchNews
//            cell.modelPS.onNext(it)
//            return cell
        default: return UITableViewCell()
        }
    })

    override func upView() {
        self.navigationItem.titleView = search
        search.placeholder = "请输入搜索的课程"
        XS_NetWork.requestJson("/setting/querySettingByKey", parameters: ["key":"search_placeholder"])
            .subscribe(onNext: { [weak self] resp in
                guard let `self` = self, resp.success, let text = resp.data as? String else { return }
                self.search.placeholder = text
            }).disposed(by: disposeBag)
        let leftView = UIView(frame: CGRect(x: 0, y: 0, width: .scale*32, height: .scale*32))
        let searchImgV = UIImageView(image: UIImage(named: "icon_16px_搜索备份"))
        searchImgV.frame = CGRect(x: 8, y: 8, width: 16, height: 16) * .scale
        leftView.addSubview(searchImgV)
        search.leftView = leftView
        search.leftViewMode = .always
        search.placeholderColor = #colorLiteral(red: 0.768627451, green: 0.7764705882, blue: 0.8039215686, alpha: 1)
        search.font = .xsFont(name: .regular, .scale*12)
        search.layer.cornerRadius = .scale*16
        search.layer.backgroundColor = #colorLiteral(red: 0.968627451, green: 0.968627451, blue: 0.968627451, alpha: 1)
        search.returnKeyType = .search
        search.rx.controlEvent(.editingDidEndOnExit)
            .subscribe(onNext: { [weak self] in
                guard let `self` = self else { return }
                self.search(self.search.text ?? "")
            }).disposed(by: disposeBag)
        search.rx.controlEvent(.editingChanged)
            .subscribe(onNext: { [weak self] in
                guard let `self` = self else { return }
                if self.search.text?.count == 0 {
                    XD_BlankPageView.hiddenBlankPageView(superView: self.table)
                    self.reloadHistory()
                    self.table.isHidden = true
                }
            }).disposed(by: disposeBag)
        
        view.addSubview(searchView)
        searchView.snp.makeConstraints({$0.edges.equalToSuperview()})
        loadSearchView()
        
        table.showsVerticalScrollIndicator = false
        table.bounces = false
        table.backgroundColor = #colorLiteral(red: 0.9764705882, green: 0.9803921569, blue: 1, alpha: 1)
        table.separatorStyle = .none
        table.sectionFooterHeight = .scale*8
        table.tableHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: .screenWidth, height: 0.01))
        table.tableFooterView = UIView(frame: CGRect(x: 0, y: 0, width: .screenWidth, height: 0.01))
        table.register(XS_SearchCurriculum.self, forCellReuseIdentifier: "课程")
        table.register(XS_SearchRecruitment.self, forCellReuseIdentifier: "就业")
//        table.register(XS_SearchNews.self, forCellReuseIdentifier: "资讯")
        table.isHidden = true
        table.contentInsetAdjustmentBehavior = .never
        view.addSubview(table)
        table.snp.makeConstraints({
            $0.edges.equalToSuperview()
        })
        table.rx.setDelegate(self)
            .disposed(by: disposeBag)
        table.rx.modelSelected(SearchType.self)
            .asDriver()
            .drive(onNext: { [weak self] type in
                guard let `self` = self else { return }
                switch type {
                case let .curriculum(item):
                    let vc = item.curriculumForm == "online" ? XS_KeChengVC() : XS_KCXianxiaVC()
                    vc.id = "\(item.id)"
                    XS_NVC.shared.pushViewController(vc, animated: true)
                case let .recruitment(item):
                    XS_NetWork.requestJson("/recruitment/queryRecruitmentById", parameters: ["id":item.id])
                        .mapModel(type: XS_queryRecruitmentListM.self)
                        .subscribe(onNext: { model, resp in
                            guard resp.success, let model = model else { return }
                            let vc = XS_ZhaopinDetailVC()
                            vc.model = model
                            XS_NVC.shared.pushViewController(vc, animated: true)
                        }).disposed(by: self.disposeBag)
                case let .news(item):
//                    let vc = XS_WebPageVC("/Home?id=\(item.id)")
                    let vc = XS_WebPageVC(item.shareUrl)
                    vc.isShare = true
                    XS_NVC.shared.pushViewController(vc, animated: true)
                }
            }).disposed(by: disposeBag)
        
        dataPS.asDriver(onErrorJustReturn: XS_searchQueryM())
            .flatMapLatest { model in
                if (model.curriculum.records.count + model.recruitment.records.count + model.news.records.count) == 0 {
                    XD_BlankPageView.blankPage(superView: self.table, imgName: "缺省页_暂无内容", detailStr: "暂无内容~", btnTitle: "去首页看看", bottomDetailStr: "") {
                        if let tbc = XS_NVC.shared.viewControllers.first as? XS_TBC {
                            tbc.selectedIndex = 0
                        }
                        XS_NVC.shared.popToRootViewController(animated: true)
                    }
                } else {
                    XD_BlankPageView.hiddenBlankPageView(superView: self.table)
                }
                if model.curriculum.total == 0 {
                    return Driver.just([SectionModel<(String, Int), SearchType>(model: ("就业",model.recruitment.total), items: model.recruitment.records.compactMap({ SearchType.recruitment($0) }))
                    ])
                } else if model.recruitment.total == 0 {
                    return Driver.just([
                        SectionModel<(String, Int), SearchType>(model: ("课程",model.curriculum.total), items: model.curriculum.records.compactMap({ SearchType.curriculum($0) }))
                    ])
                } else {
                    return Driver.just([
                        SectionModel<(String, Int), SearchType>(model: ("课程",model.curriculum.total), items: model.curriculum.records.compactMap({ SearchType.curriculum($0) })),
                        SectionModel<(String, Int), SearchType>(model: ("就业",model.recruitment.total), items: model.recruitment.records.compactMap({ SearchType.recruitment($0) }))
                        //                    SectionModel<(String, Int), SearchType>(model: ("资讯",model.news.total), items: model.news.records.compactMap({ SearchType.news($0) }))
                    ])
                }
            } .drive(table.rx.items(dataSource: dataSource))
            .disposed(by: disposeBag)
    }

    func loadSearchView() {
        let label1 = UILabel.xsLabel(size: .scale*16, fontName: .medium, color: #colorLiteral(red: 0.2196078431, green: 0.2352941176, blue: 0.2470588235, alpha: 1), text: "搜索记录")
        searchView.addSubview(label1)
        label1.snp.makeConstraints({
            $0.left.equalTo(.scale*16)
            $0.top.equalTo(.scale*17)
        })
        let button = XS_NoHighlightBtn()
        button.setImage(UIImage(named: "icon_12px_删除"), for: .normal)
        button.setTitle("清除记录", for: .normal)
        button.setTitleColor(#colorLiteral(red: 0.4470588235, green: 0.4666666667, blue: 0.4862745098, alpha: 1), for: .normal)
        button.titleLabel?.font = .xsFont(name: .regular, .scale*14)
        searchView.addSubview(button)
        button.snp.makeConstraints({
            $0.centerY.equalTo(label1.snp.centerY)
            $0.right.equalTo(-.scale*17)
        })
        
        let historyView = UIView(frame: CGRect(x: 0, y: .scale*56, width: .screenWidth, height: .scale*128))
        historyView.tag = 1111
        searchView.addSubview(historyView)
        reloadHistory()
        button.rx.tap.asDriver()
            .drive(onNext: { [weak self] in
                UserDefaults.standard.setValue([], forKey: .xsKey_history)
                self?.reloadHistory()
            }).disposed(by: disposeBag)
        
        
        let label2 = UILabel.xsLabel(size: .scale*16, fontName: .medium, color: #colorLiteral(red: 0.2196078431, green: 0.2352941176, blue: 0.2470588235, alpha: 1), text: "热门搜索")
        searchView.addSubview(label2)
        label2.snp.makeConstraints({
            $0.left.equalTo(.scale*16)
            $0.top.equalTo(.scale*201)
        })
        
        XS_NetWork.requestJson("/search/queryHotSearch")
            .subscribe(onNext: { [weak self] resp in
                guard let `self` = self, let arr = resp.data as? [String] else { return }
                var top = .scale*240
                var left = .scale*16
                for text in arr {
                    let btn = self.getButton(text, isImg: true)
                    let width = text.size(withFont: UIFont.xsFont(name: .regular, .scale*14)).width + .scale*42
                    
                    if left + width + .scale*16 > .screenWidth {
                        top += .scale*(32+16)
                        left = .scale*16
                    }
                    
                    btn.frame = CGRect(x: left, y: top, width: width, height: .scale*32)
                    self.searchView.addSubview(btn)
                    
                    left += width + .scale*16
                }
            }).disposed(by: disposeBag)
    }
    
    func getButton(_ text: String, isImg: Bool) -> UIButton {
        let btn = XS_NoHighlightBtn()
        btn.layer.cornerRadius = .scale*16
        btn.layer.backgroundColor = #colorLiteral(red: 0.968627451, green: 0.968627451, blue: 0.968627451, alpha: 1)
        let label = UILabel.xsLabel(size: .scale*14, fontName: .regular, color: #colorLiteral(red: 0.2196078431, green: 0.2352941176, blue: 0.2470588235, alpha: 1), text: text)
        btn.addSubview(label)
        if isImg {
            let imgV = UIImageView(image: UIImage(named: "icon_14px_热门"))
            btn.addSubview(imgV)
            imgV.snp.makeConstraints({
                $0.width.height.equalTo(.scale*14)
                $0.left.equalTo(.scale*8)
                $0.centerY.equalToSuperview()
            })
            label.snp.makeConstraints({
                $0.centerY.equalToSuperview()
                $0.left.equalTo(imgV.snp.right).offset(.scale*4)
            })
        } else {
            label.snp.makeConstraints({
                $0.center.equalToSuperview()
            })
        }
        btn.rx.tap.asDriver()
            .drive(onNext: { [weak self] in
                guard let `self` = self else { return }
                self.search.text = text
                self.search(text)
            }).disposed(by: disposeBag)
        return btn
    }
    
    func reloadHistory() {
        guard let view = searchView.viewWithTag(1111) else { return }
        view.removeSubviews()
        guard let arr = UserDefaults.standard.array(forKey: .xsKey_history) as? [String], arr.count > 0 else { return }
        var top: CGFloat = 0
        var left = .scale*16
        for text in arr {
            let btn = getButton(text, isImg: false)
            let width = text.size(withFont: UIFont.xsFont(name: .regular, .scale*14)).width + .scale*32
            
            if left + width + .scale*16 > .screenWidth {
                top += .scale*(32+16)
                left = .scale*16
            }
            
            btn.frame = CGRect(x: left, y: top, width: width, height: .scale*32)
            view.addSubview(btn)
            
            left += width + .scale*16
        }
    }
    
    func search(_ text: String) {
        guard text.count > 0 else {
            reloadHistory()
            table.isHidden = true
            return
        }
        var arr = UserDefaults.standard.array(forKey: .xsKey_history) as? [String] ?? []
        arr.removeAll { $0 == text }
        arr.insert(text, at: 0)
        let texts: [String] = [] + arr.prefix(5)
        UserDefaults.standard.set(texts, forKey: .xsKey_history)
        
        
        XS_NetWork.requestJson("/search/searchQuery", parameters: ["searchWhere":text])
            .mapModel(type: XS_searchQueryM.self)
            .subscribe(onNext: { [weak self] model, resp in
                guard let `self` = self, resp.success, let model = model else { return }
                self.dataPS.onNext(model)
                self.table.isHidden = false
            }).disposed(by: disposeBag)
    }
}

extension XS_SearchVC: UITableViewDelegate {
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        switch indexPath.section {
        case 1: return .scale*116
        default: return .scale*104
        }
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return .scale*40
    }
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let (text, count) = dataSource.sectionModels[section].model
//        return getHeaderView(text, count: count)
        if count > 0 {
            return getHeaderView(text, count: count)
        }
        return nil
    }
    func getHeaderView(_ str: String, count: Int) -> UIView {
        let view = UIView()
        view.backgroundColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
        let label = UILabel.xsLabel(size: .scale*18, fontName: .semibold, color: #colorLiteral(red: 0.2196078431, green: 0.2352941176, blue: 0.2470588235, alpha: 1), text: str)
        view.addSubview(label)
        label.snp.makeConstraints({
            $0.left.equalTo(.scale*16)
            $0.bottom.equalToSuperview()
        })
        let text = NSMutableAttributedString()
        do {
            let attr = NSMutableAttributedString(string: "共 ")
            attr.yy_font = .xsFont(name: .regular, .scale*14)
            attr.yy_color = #colorLiteral(red: 0.6666666667, green: 0.6941176471, blue: 0.7176470588, alpha: 1)
            text.append(attr)
        }
        do {
            let attr = NSMutableAttributedString(string: "\(count)")
            attr.yy_font = .xsFont(name: .medium, .scale*14)
            attr.yy_color = #colorLiteral(red: 0.1647058824, green: 0.7411764706, blue: 0.6117647059, alpha: 1)
            text.append(attr)
        }
        do {
            let attr = NSMutableAttributedString(string: " 个")
            attr.yy_font = .xsFont(name: .regular, .scale*14)
            attr.yy_color = #colorLiteral(red: 0.6666666667, green: 0.6941176471, blue: 0.7176470588, alpha: 1)
            text.append(attr)
        }
        let cLab = UILabel()
        cLab.attributedText = text
        view.addSubview(cLab)
        cLab.snp.makeConstraints({
            $0.right.equalTo(-.scale*31)
            $0.bottom.equalToSuperview()
        })
        let imgIV = UIImageView.init(image: UIImage.init(named: "icon_12px_更多"))
        view.addSubview(imgIV)
        imgIV.snp.makeConstraints { (make) in
            make.centerY.equalTo(cLab)
            make.right.equalTo(-.scale * 16)
            make.width.height.equalTo(.scale * 12)
        }
        
        let tap = UITapGestureRecognizer()
        view.addGestureRecognizer(tap)
        _ = tap.rx.event.asDriver()
            .drive(onNext: { [weak self] _ in
                let vc = XS_SearchTongyongVC()
                vc.title = str
                switch str {
                case "课程": vc.type = .curriculum
                case "就业": vc.type = .recruitment
//                case "资讯": vc.type = .news
                default: return
                }
                vc.searchWhere = self?.search.text ?? ""
                self?.navigationController?.pushViewController(vc, animated: true)
            })
        return view
    }
}

//class XS_SearchCurriculumXianXia: XS_BaseTCell { // Xianxia
//    lazy var modelPS = PublishSubject<XS_SearchVC.SearchType>()
//
//    override func getLineEdgeInsets() -> UIEdgeInsets {
//        UIEdgeInsets(top: 0, left: .scale*15, bottom: 0, right: -.scale*17)
//    }
//
//    override func upView() {
//        super.upView()
//        loadLine()
//
//        let imgV = UIImageView()
//        imgV.layer.cornerRadius = .scale*4
//        imgV.layer.masksToBounds = true
//        contentView.addSubview(imgV)
//        imgV.snp.makeConstraints({
//            $0.width.equalTo(.scale*100)
//            $0.height.equalTo(.scale*72)
//            $0.left.equalTo(.scale*15)
//            $0.centerY.equalToSuperview()
//        })
//
//        let tagsView = UIView(frame: CGRect(x: 0, y: 0, width: 49, height: 18) * .scale)
//        imgV.addSubview(tagsView)
//        let sLayer = CAShapeLayer()
//        sLayer.fillColor = #colorLiteral(red: 0.9294117647, green: 0.3960784314, blue: 0.2470588235, alpha: 1)
//        sLayer.path = UIBezierPath(roundedRect: tagsView.bounds, byRoundingCorners: [.bottomRight], cornerRadii: CGSize(width: 4, height: 4) * .scale).cgPath
//        tagsView.layer.addSublayer(sLayer)
//        let tagLabel = UILabel.xsLabel(size: .scale*10, fontName: .medium, color: #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0), alignment: .center, text: "限时免费")
//        tagsView.addSubview(tagLabel)
//        tagLabel.snp.makeConstraints({
//            $0.center.equalToSuperview()
//        })
//
//        let layerView = UIView()
//        layerView.frame = CGRect(x: 0, y: 0, width: .scale*45, height: .scale*18)
//        layerView.corner(byRoundingCorners: .bottomRight, radii: .scale*4)
//        layerView.alpha = 1
//        // fillCode
//        let bglayer1 = CAGradientLayer()
//        bglayer1.colors = [UIColor(red: 1, green: 0.91, blue: 0.73, alpha: 1).cgColor, UIColor(red: 0.98, green: 0.84, blue: 0.59, alpha: 1).cgColor]
//        bglayer1.locations = [0, 1]
//        bglayer1.frame = layerView.bounds
//        layerView.layer.addSublayer(bglayer1)
//        bglayer1.startPoint = CGPoint(x: 1.00, y: 0.50)
//        bglayer1.endPoint = CGPoint(x: -0.00, y: 0.50)
//        imgV.addSubview(layerView)
//        let label = UILabel.xsLabel(size: .scale*10, fontName: .medium, color: #colorLiteral(red: 0.5803921569, green: 0.3490196078, blue: 0, alpha: 1), text: "VIP免费")
//        layerView.addSubview(label)
//        label.snp.makeConstraints({
//            $0.center.equalToSuperview()
//        })
//
//        let label1 = UILabel.xsLabel(size: .scale*14, fontName: .medium, color: #colorLiteral(red: 0.2829915285, green: 0.3015331626, blue: 0.3147756159, alpha: 1))
//        contentView.addSubview(label1)
//        label1.snp.makeConstraints {
//            $0.top.equalToSuperview()
//            $0.left.equalTo(imgV.snp.right).offset(.scale*12)
//            $0.right.lessThanOrEqualToSuperview().offset(-.scale*8)
//        }
//        let icon = UIImageView(image: UIImage(named: "icon_12px_定位"))
//        icon.frame = CGRect(x: .scale*112, y: .scale*28, width: .scale*12, height: .scale*12)
//        contentView.addSubview(icon)
//        let label2 = UILabel.xsLabel(size: .scale*12, fontName: .regular, color: #colorLiteral(red: 0.4470588235, green: 0.4666666667, blue: 0.4862745098, alpha: 1))
//        contentView.addSubview(label2)
//        label2.snp.makeConstraints {
//            $0.centerY.equalTo(icon.snp.centerY)
//            $0.left.equalTo(icon.snp.right).offset(.scale*4)
//            $0.right.lessThanOrEqualToSuperview().offset(-.scale*8)
//        }
//        let label3 = UILabel.xsLabel(size: .scale*12, fontName: .regular, color: #colorLiteral(red: 0.6666666667, green: 0.6941176471, blue: 0.7176470588, alpha: 1))
//        contentView.addSubview(label3)
//        label3.snp.makeConstraints {
//            $0.bottom.equalTo(-.scale*16)
//            $0.left.equalTo(imgV.snp.right).offset(.scale*12)
//            $0.width.lessThanOrEqualTo(.scale*150)
//        }
//        let fm = DateFormatter()
//        fm.dateFormat = "yyyy-MM-dd HH:mm:ss"
//
//        let label4 = UILabel()
//
//        contentView.addSubview(label4)
//        label4.snp.makeConstraints({
//            $0.right.equalToSuperview()
//            $0.bottom.equalTo(-.scale*16)
//        })
//
//        modelPS.subscribe(onNext: { type in
//            guard case let .curriculum(item) = type else { return }
//            imgV.sd_setImage(with: URL(string: item.curriculumImgUrl))
//            let (p, _) = xsGetPrice(vipIsFree: item.vipIsFree, isFree: item.isFree, vipPrice: item.vipPrice, discountPrice: item.discountPrice, price: item.price)
//            let text = NSMutableAttributedString()
//            if p.count > 0 {
//                let attr = NSMutableAttributedString(string: "￥")
//                attr.yy_font = .xsFont(name: .medium, .scale*14)
//                text.append(attr)
//            }
//            do {
//                let attr = NSMutableAttributedString(string: p.count > 0 ? p : "免费")
//                attr.yy_font = .xsFont(name: .medium, .scale*16)
//                text.append(attr)
//            }
//            text.yy_color = #colorLiteral(red: 0.9294117647, green: 0.3960784314, blue: 0.2470588235, alpha: 1)
//            text.yy_alignment = .right
//            label4.attributedText = text
//            if let date = fm.date(from: item.startTime) {
//                let fm1 = DateFormatter()
//                fm1.dateFormat = "d.M EE"
//                label3.text = fm1.string(from: date)
//            }
//            label2.text = item.offlineAddress
//            label1.text = item.curriculumName
//            tagsView.isHidden = true
//            layerView.isHidden = true
//            if item.isFree == "userFree" {
//                tagsView.isHidden = false
//            } else if item.vipIsFree == "vipFree" {
//                layerView.isHidden = false
//            }
//        }).disposed(by: disposeBag)
//    }
//}

class XS_SearchCurriculum: XS_BaseTCell { // 课程
    lazy var modelPS = PublishSubject<XS_SearchVC.SearchType>()
    
    override func getLineEdgeInsets() -> UIEdgeInsets {
        UIEdgeInsets(top: 0, left: .scale*15, bottom: 0, right: -.scale*17)
    }
    
    override func upView() {
        super.upView()
        loadLine()
        
        let imgV = UIImageView()
        imgV.layer.cornerRadius = .scale*4
        imgV.layer.masksToBounds = true
        contentView.addSubview(imgV)
        imgV.snp.makeConstraints({
            $0.width.equalTo(.scale*112)
            $0.height.equalTo(.scale*80)
            $0.top.left.equalTo(.scale * 16)
        })
        let label = UILabel.xsLabel(size: .scale*16, fontName: .medium, color: #colorLiteral(red: 0.2196078431, green: 0.2352941176, blue: 0.2470588235, alpha: 1))
        contentView.addSubview(label)
        label.snp.makeConstraints({
            $0.left.equalTo(imgV.snp.right).offset(.scale*12)
            $0.top.equalTo(imgV)
            $0.right.equalTo(-.scale * 16)
        })
        
        let people = UILabel.xsLabel(size: .scale*13, fontName: .regular, color: #colorLiteral(red: 0.6666666667, green: 0.6941176471, blue: 0.7176470588, alpha: 1))
        contentView.addSubview(people)
        people.snp.makeConstraints({
            $0.left.equalTo(imgV.snp.right).offset(.scale*12)
            $0.bottom.equalTo(imgV)
        })
        
        let price = UILabel.xsLabel(size: .scale*13, fontName: .semibold, color: #colorLiteral(red: 0.9294117647, green: 0.3960784314, blue: 0.2470588235, alpha: 1))
        contentView.addSubview(price)
        price.snp.makeConstraints({
            $0.right.equalTo(-.scale * 16)
            $0.bottom.equalTo(imgV)
        })
        
        modelPS.subscribe(onNext: { type in
            guard case let .curriculum(model) = type else { return }
            let (p, _) = xsGetPrice(vipIsFree: model.vipIsFree, isFree: model.isFree, vipPrice: model.vipPrice, discountPrice: model.discountPrice, price: model.price)
            imgV.sd_setImage(with: URL(string: model.curriculumImgUrl))
            label.text = model.curriculumName
            people.text = "\(model.purchaseNum)人加入学习"
            _ = model.isFree == "userFree"
            price.text = "共\(model.curriculumNum)节 | " + (p.count>0 ? "￥\(p)" : "免费")
            if let infoModel = XS_Singleton.shared.infoModel, infoModel.userBO.userType == "user", (Double(model.vipPrice) ?? 0) <= 0, (Double(model.discountPrice) ?? 0) <= 0 {
                let tagsView = UIView(frame: CGRect(x: 0, y: 0, width: 49, height: 18) * .scale)
                imgV.addSubview(tagsView)
                let sLayer = CAShapeLayer()
                sLayer.fillColor = #colorLiteral(red: 0.9294117647, green: 0.3960784314, blue: 0.2470588235, alpha: 1)
                sLayer.path = UIBezierPath(roundedRect: tagsView.bounds, byRoundingCorners: [.bottomRight], cornerRadii: CGSize(width: 4, height: 4) * .scale).cgPath
                tagsView.layer.addSublayer(sLayer)
                let tagLabel = UILabel.xsLabel(size: .scale*10, fontName: .medium, color: #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0), alignment: .center, text: "限时免费")
                tagsView.addSubview(tagLabel)
                tagLabel.snp.makeConstraints({
                    $0.center.equalToSuperview()
                })
            } else if (Double(model.vipPrice) ?? 0) <= 0, (Double(model.discountPrice) ?? 0) > 0  {
                let layerView = UIView()
                layerView.frame = CGRect(x: 0, y: 0, width: .scale*45, height: .scale*18)
                layerView.corner(byRoundingCorners: .bottomRight, radii: .scale*4)
                layerView.alpha = 1
                // fillCode
                let bglayer1 = CAGradientLayer()
                bglayer1.colors = [UIColor(red: 1, green: 0.91, blue: 0.73, alpha: 1).cgColor, UIColor(red: 0.98, green: 0.84, blue: 0.59, alpha: 1).cgColor]
                bglayer1.locations = [0, 1]
                bglayer1.frame = layerView.bounds
                layerView.layer.addSublayer(bglayer1)
                bglayer1.startPoint = CGPoint(x: 1.00, y: 0.50)
                bglayer1.endPoint = CGPoint(x: -0.00, y: 0.50)
                imgV.addSubview(layerView)
                
                let label = UILabel.xsLabel(size: .scale*10, fontName: .medium, color: #colorLiteral(red: 0.5803921569, green: 0.3490196078, blue: 0, alpha: 1), text: "VIP免费")
                layerView.addSubview(label)
                label.snp.makeConstraints({
                    $0.center.equalToSuperview()
                })
            }
            
            var lastV: UIView?
            for text in (model.label.components(separatedBy: ",")) {
                let tagV = self.getTags(text)
                self.contentView.addSubview(tagV)
                tagV.snp.makeConstraints { (make) in
                    make.top.equalTo(label.snp.bottom).offset(.scale * 5)
                    make.height.equalTo(.scale * 16)
                    if let last = lastV {
                        make.left.equalTo(last.snp.right).offset(.scale * 6)
                    } else {
                        make.left.equalTo(imgV.snp.right).offset(.scale * 12)
                    }
                }
                lastV = tagV
            }
        }).disposed(by: disposeBag)
    }
    
    
    func getTags(_ text: String) -> UIView {
        let tabBgV = UIView()
        tabBgV.layer.borderWidth = 0.5
        tabBgV.layer.borderColor = UIColor(red: 0.16, green: 0.74, blue: 0.61, alpha: 1.00).cgColor
        tabBgV.layer.cornerRadius = .scale * 4
        
        let tagLab = UILabel.xsLabel(size: .scale * 10, color:UIColor(red: 0.16, green: 0.74, blue: 0.61, alpha: 1.00), alignment: .center, text: text)
        tabBgV.addSubview(tagLab)
        tagLab.snp.makeConstraints { (make) in
            make.top.bottom.equalToSuperview()
            make.right.equalTo(-.scale * 5)
            make.left.equalTo(.scale * 5)
        }
        return tabBgV
    }
}
class XS_SearchRecruitment: XS_BaseTCell { // 就业
    lazy var modelPS = PublishSubject<XS_SearchVC.SearchType>()
    
    override func getLineEdgeInsets() -> UIEdgeInsets {
        UIEdgeInsets(top: 0, left: .scale*15, bottom: 0, right: -.scale*18)
    }
    
    override func upView() {
        super.upView()
        loadLine()
        
//        let imgV = UIImageView()
//        imgV.layer.cornerRadius = .scale*2
//        imgV.layer.masksToBounds = true
//        contentView.addSubview(imgV)
//        imgV.snp.makeConstraints({
//            $0.width.height.equalTo(.scale*24)
//            $0.left.equalTo(.scale*15)
//            $0.bottom.equalTo(-.scale*16)
//        })
         
        let label1 = UILabel.xsLabel(size: .scale*16, fontName: .medium, color: #colorLiteral(red: 0.9294117647, green: 0.3960784314, blue: 0.2470588235, alpha: 1), alignment: .right, text: "8-12K")
        contentView.addSubview(label1)
        label1.snp.makeConstraints({
            $0.top.equalTo(.scale*16)
            $0.right.equalTo(-.scale*16)
        })
        
        let label = UILabel.xsLabel(size: .scale*16, fontName: .medium, color: #colorLiteral(red: 0.2196078431, green: 0.2352941176, blue: 0.2470588235, alpha: 1), text: "招聘职位招聘职位招聘职位")
        contentView.addSubview(label)
        label.snp.makeConstraints {
            $0.left.top.equalTo(.scale*16)
            $0.right.lessThanOrEqualTo(label1.snp.left).offset(-.scale*8)
        }
        
        let label2 = UILabel.xsLabel(size: .scale*14, fontName: .regular, color: #colorLiteral(red: 0.4470588235, green: 0.4666666667, blue: 0.4862745098, alpha: 1), text: "XXX公司")
        contentView.addSubview(label2)
        label2.snp.makeConstraints({
            $0.left.equalTo(.scale * 16)
            $0.bottom.equalTo(-.scale * 18)
        })
        let label3 = UILabel.xsLabel(size: .scale*14, fontName: .regular, color: #colorLiteral(red: 0.4470588235, green: 0.4666666667, blue: 0.4862745098, alpha: 1), alignment: .right, text: "北京市 朝阳区")
        contentView.addSubview(label3)
        label3.snp.makeConstraints({
            $0.right.equalTo(-.scale * 16)
            $0.centerY.equalTo(label2.snp.centerY)
        })
        
        let (v1, lab1) = getTagView()
        contentView.addSubview(v1)
        v1.snp.makeConstraints({
            $0.height.equalTo(.scale*20)
            $0.top.equalTo(.scale*46)
            $0.left.equalTo(.scale*15)
        })
        let (v2, lab2) = getTagView()
        contentView.addSubview(v2)
        v2.snp.makeConstraints({
            $0.height.equalTo(.scale*20)
            $0.top.equalTo(.scale*46)
            $0.left.equalTo(v1.snp.right).offset(.scale*8)
        })
        
        modelPS.subscribe(onNext: { [weak self] type in
            guard let _ = self, case let .recruitment(model) = type else { return }
//            imgV.sd_setImage(with: URL(string: model.companyLogoUrl))
            label.text = model.positionName
            label1.text = model.salaryRange
            label2.text = model.companyName
//            label3.text = item.detailAddress
            label3.text = model.workPlace
            lab1.text = model.experienceRequirement
            lab2.text = model.industryName
        }).disposed(by: disposeBag)
    }
    
    func getTagView() -> (UIView, UILabel) {
        let view = UIView()
        view.layer.cornerRadius = .scale*10
        view.layer.backgroundColor = #colorLiteral(red: 0.968627451, green: 0.968627451, blue: 0.968627451, alpha: 1)
        let label = UILabel.xsLabel(size: .scale*12, fontName: .regular, color: UIColor(red: 0.16, green: 0.74, blue: 0.61, alpha: 1.0))
        view.addSubview(label)
        label.snp.makeConstraints({
            $0.center.equalToSuperview()
            $0.right.equalTo(-.scale*6)
        })
        return (view, label)
    }
}
class XS_SearchNews: XS_BaseTCell { // 资讯
    lazy var modelPS = PublishSubject<XS_SearchVC.SearchType>()
    
    override func getLineEdgeInsets() -> UIEdgeInsets {
        UIEdgeInsets(top: 0, left: .scale*14, bottom: 0, right: -.scale*18)
    }
    
    override func upView() {
        super.upView()
        loadLine()
        
        let imgV = UIImageView()
        imgV.layer.cornerRadius = .scale*4
        imgV.layer.masksToBounds = true
        contentView.addSubview(imgV)
        imgV.snp.makeConstraints({
            $0.width.equalTo(.scale*100)
            $0.height.equalTo(.scale*72)
            $0.right.equalTo(-.scale*18)
            $0.centerY.equalToSuperview()
        })
            
        let label = UILabel.xsLabel(size: .scale*14, fontName: .medium, color: #colorLiteral(red: 0.2196078431, green: 0.2352941176, blue: 0.2470588235, alpha: 1), lines: 2)
        contentView.addSubview(label)
        label.snp.makeConstraints({
            $0.left.equalTo(.scale*14)
            $0.top.equalTo(.scale*16)
            $0.right.lessThanOrEqualTo(imgV.snp.left).offset(-.scale*12)
        })
        
        let label2 = UILabel.xsLabel(size: .scale*12, fontName: .regular, color: #colorLiteral(red: 0.6666666667, green: 0.6941176471, blue: 0.7176470588, alpha: 1), alignment: .right)
        contentView.addSubview(label2)
        label2.snp.makeConstraints({
            $0.bottom.equalTo(-.scale*18)
            $0.right.equalTo(imgV.snp.left).offset(-.scale*12)
        })
        
        let tagsView = UIView()
        contentView.addSubview(tagsView)
        tagsView.snp.makeConstraints({
            $0.height.equalTo(.scale*20)
            $0.left.equalTo(.scale*14)
            $0.bottom.equalTo(-.scale*16)
            $0.right.lessThanOrEqualTo(label2.snp.left)
        })
        
        modelPS.subscribe(onNext: { [weak self] type in
            guard let `self` = self, case let .news(model) = type else { return }
            imgV.sd_setImage(with: URL(string: model.newsImgUrl))
            label.text = model.title
            label2.text = "\(model.count)浏览"
            tagsView.removeSubviews()
            var last: UIView?
            for text in model.label.components(separatedBy: "，") {
                let (view, lab) = self.getTagView()
                lab.text = text
                tagsView.addSubview(view)
                view.snp.makeConstraints({
                    $0.height.top.equalToSuperview()
                    if let last = last {
                        $0.left.equalTo(last.snp.right).offset(.scale*8)
                    } else {
                        $0.left.equalToSuperview()
                    }
                })
                last = view
            }
        }).disposed(by: disposeBag)
    }
    
    func getTagView() -> (UIView, UILabel) {
        let view = UIView()
        view.layer.cornerRadius = .scale*10
        view.layer.backgroundColor = #colorLiteral(red: 0.968627451, green: 0.968627451, blue: 0.968627451, alpha: 1)
        let label = UILabel.xsLabel(size: .scale*12, fontName: .regular, color: #colorLiteral(red: 0.4470588235, green: 0.4666666667, blue: 0.4862745098, alpha: 1))
        view.addSubview(label)
        label.snp.makeConstraints({
            $0.center.equalToSuperview()
            $0.right.equalTo(-.scale*6)
        })
        return (view, label)
    }
}
